package com.zyndev.tool.validation;

import com.zyndev.tool.validation.constraints.Valid;
import com.zyndev.tool.validation.core.ValidRole;

import java.lang.reflect.Field;
import java.util.HashSet;
import java.util.Set;

/**
 * desc :
 * author: 张瑀楠
 * email : zyndev@gmail.com
 * date  : 2017/12/1 下午9:39
 * todo  :
 */
public class ValidatorImpl<T> implements Validator<T>{

    private volatile Set<ValidRole> validRoles = null;

    public void addValidRole(ValidRole validRole) {
        validRoles.add(validRole);
    }

    public ValidatorImpl() {
        if (null == validRoles) {
            synchronized (ValidatorImpl.class) {
                validRoles = new HashSet<>();
            }
        }
    }

    @Override
    public boolean validation(T t) {
        // 判断是否有 Valid 注解
        Valid valid = t.getClass().getAnnotation(Valid.class);
        if (null == valid) {
            return true;
        }

        Field[] fields = t.getClass().getDeclaredFields();
        ValidResult validResult = null;
        for (Field field: fields) {
            if(field.getAnnotations().length != 0) {
                for (ValidRole validRole : validRoles) {
                    validResult = validRole.execute(t, field);
                    if (!validResult.isValidation()) {
                        return false;
                    }
                }
            }
        }
        return true;
    }

}
